home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / utils / file / fileutil.13 / fileutil / fileutils-3.13 / src / ln.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-07-06  |  13.2 KB  |  489 lines

  1. /* `ln' program to create links between files.
  2.    Copyright (C) 86, 89, 90, 91, 95, 1996 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software Foundation,
  16.    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
  17.  
  18. /* Written by Mike Parker and David MacKenzie. */
  19.  
  20. #ifdef _AIX
  21.  #pragma alloca
  22. #endif
  23.  
  24. #include <config.h>
  25. #include <stdio.h>
  26. #include <sys/types.h>
  27. #include <getopt.h>
  28.  
  29. #include "system.h"
  30. #include "backupfile.h"
  31. #include "error.h"
  32.  
  33. int link ();            /* Some systems don't declare this anywhere. */
  34.  
  35. #ifdef S_ISLNK
  36. int symlink ();
  37. #endif
  38.  
  39. #ifdef S_ISLNK
  40. # define LINK_TYPE symbolic_link ? _("symbolic link") : _("hard link")
  41. #else
  42. # define LINK_TYPE ""
  43. #endif
  44.  
  45. /* Construct a string NEW_DEST by concatenating DEST, a slash, and
  46.    basename(SOURCE) in alloca'd memory.  Don't modify DEST or SOURCE.  */
  47.  
  48. #define PATH_BASENAME_CONCAT(new_dest, dest, source)            \
  49.     do                                    \
  50.       {                                    \
  51.     char *source_base;                        \
  52.     char *tmp_source;                        \
  53.                                     \
  54.     tmp_source = (char *) alloca (strlen ((source)) + 1);        \
  55.     strcpy (tmp_source, (source));                    \
  56.     strip_trailing_slashes (tmp_source);                \
  57.     source_base = basename (tmp_source);                \
  58.                                     \
  59.     (new_dest) = (char *) alloca (strlen ((dest)) + 1        \
  60.                       + strlen (source_base) + 1);    \
  61.     stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
  62.       }                                    \
  63.     while (0)
  64.  
  65. char *basename ();
  66. char *dirname ();
  67. enum backup_type get_version ();
  68. int isdir ();
  69. int yesno ();
  70. void strip_trailing_slashes ();
  71. char *stpcpy ();
  72.  
  73. /* The name by which the program was run, for error messages.  */
  74. char *program_name;
  75.  
  76. /* A pointer to the function used to make links.  This will point to either
  77.    `link' or `symlink'. */
  78. static int (*linkfunc) ();
  79.  
  80. /* If nonzero, make symbolic links; otherwise, make hard links.  */
  81. static int symbolic_link;
  82.  
  83. /* If nonzero, ask the user before removing existing files.  */
  84. static int interactive;
  85.  
  86. /* If nonzero, remove existing files unconditionally.  */
  87. static int remove_existing_files;
  88.  
  89. /* If nonzero, list each file as it is moved. */
  90. static int verbose;
  91.  
  92. /* If nonzero, allow the superuser to make hard links to directories. */
  93. static int hard_dir_link;
  94.  
  95. /* If nonzero, and the specified destination is a symbolic link to a
  96.    directory, treat it just as if it were a directory.  Otherwise, the
  97.    command `ln --force --no-dereference file symlink-to-dir' deletes
  98.    symlink-to-dir before creating the new link.  */
  99. static int dereference_dest_dir_symlinks = 1;
  100.  
  101. /* If nonzero, display usage information and exit.  */
  102. static int show_help;
  103.  
  104. /* If nonzero, print the version on standard output and exit.  */
  105. static int show_version;
  106.  
  107. static struct option const long_options[] =
  108. {
  109.   {"backup", no_argument, NULL, 'b'},
  110.   {"directory", no_argument, &hard_dir_link, 1},
  111.   {"no-dereference", no_argument, NULL, 'n'},
  112.   {"force", no_argument, NULL, 'f'},
  113.   {"interactive", no_argument, NULL, 'i'},
  114.   {"suffix", required_argument, NULL, 'S'},
  115.   {"symbolic", no_argument, &symbolic_link, 1},
  116.   {"verbose", no_argument, &verbose, 1},
  117.   {"version-control", required_argument, NULL, 'V'},
  118.   {"help", no_argument, &show_help, 1},
  119.   {"version", no_argument, &show_version, 1},
  120.   {NULL, 0, NULL, 0}
  121. };
  122.  
  123. /* Return nonzero if SOURCE and DEST point to the same name in the same
  124.    directory.  */
  125.  
  126. static int
  127. same_name (const char *source, const char *dest)
  128. {
  129.   struct stat source_dir_stats;
  130.   struct stat dest_dir_stats;
  131.   char *source_dirname, *dest_dirname;
  132.  
  133.   source_dirname = dirname (source);
  134.   dest_dirname = dirname (dest);
  135.   if (source_dirname == NULL || dest_dirname == NULL)
  136.     error (1, 0, _("virtual memory exhausted"));
  137.  
  138.   if (stat (source_dirname, &source_dir_stats))
  139.     /* Shouldn't happen.  */
  140.     error (1, errno, "%s", source_dirname);
  141.  
  142.   if (stat (dest_dirname, &dest_dir_stats))
  143.     /* Shouldn't happen.  */
  144.     error (1, errno, "%s", dest_dirname);
  145.  
  146.   free (source_dirname);
  147.   free (dest_dirname);
  148.  
  149.   return (source_dir_stats.st_dev == dest_dir_stats.st_dev
  150.       && source_dir_stats.st_ino == dest_dir_stats.st_ino
  151.       && STREQ (basename (source), basename (dest)));
  152. }
  153.  
  154. /* Make a link DEST to the (usually) existing file SOURCE.
  155.    Symbolic links to nonexistent files are allowed.
  156.    If DEST is a directory, put the link to SOURCE in that directory.
  157.    Return 1 if there is an error, otherwise 0.  */
  158.  
  159. static int
  160. do_link (const char *source, const char *dest)
  161. {
  162.   struct stat source_stats;
  163.   struct stat dest_stats;
  164.   char *dest_backup = NULL;
  165.   int lstat_status;
  166.  
  167.   /* Use stat here instead of lstat.
  168.      On SVR4, link does not follow symlinks, so this check disallows
  169.      making hard links to symlinks that point to directories.  Big deal.
  170.      On other systems, link follows symlinks, so this check is right.  */
  171.   if (!symbolic_link)
  172.     {
  173.       if (stat (source, &source_stats) != 0)
  174.     {
  175.       error (0, errno, "%s", source);
  176.       return 1;
  177.     }
  178.       if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
  179.     {
  180.       error (0, 0, _("%s: hard link not allowed for directory"), source);
  181.       return 1;
  182.     }
  183.     }
  184.  
  185.   lstat_status = lstat (dest, &dest_stats);
  186.  
  187.   if (lstat_status != 0 && errno != ENOENT)
  188.     {
  189.       error (0, errno, "%s", dest);
  190.       return 1;
  191.     }
  192.  
  193.   /* If --force (-f) has been specified without --backup, then before
  194.      making a link ln must remove the destination file if it exists.
  195.      (with --backup, it just renames any existing destination file)
  196.      But if the source and destination are the same, don't remove
  197.      anything and fail right here.  */
  198.   if (remove_existing_files
  199.       && lstat_status == 0
  200.       /* Allow `ln -sf --backup k k' to succeed in creating the
  201.      self-referential symlink, but don't allow the hard-linking
  202.      equivalent: `ln -f k k' (with or without --backup) to get
  203.      beyond this point, because the error message you'd get is
  204.      misleading.  */
  205.       && (backup_type == none || !symlink)
  206.       && (!symlink || stat (source, &source_stats) == 0)
  207.       && source_stats.st_dev == dest_stats.st_dev
  208.       && source_stats.st_ino == dest_stats.st_ino
  209.       /* The following detects whether removing DEST will also remove
  210.       SOURCE.  If the file has only one link then both are surely
  211.       the same link.  Otherwise check whether they point to the same
  212.      name in the same directory.  */
  213.       && (source_stats.st_nlink == 1 || same_name (source, dest)))
  214.     {
  215.       error (0, 0, _("`%s' and `%s' are the same file"), source, dest);
  216.       return 1;
  217.     }
  218.  
  219.   /* If the destination is a directory or (it is a symlink to a directory
  220.      and the user has not specified --no-dereference), then form the
  221.      actual destination name by appending basename (source) to the
  222.      specified destination directory.  */
  223.   if ((lstat_status == 0
  224.        && S_ISDIR (dest_stats.st_mode))
  225. #ifdef S_ISLNK
  226.       || (dereference_dest_dir_symlinks
  227.       && (S_ISLNK (dest_stats.st_mode)
  228.       && isdir (dest)))
  229. #endif
  230.      )
  231.     {
  232.       /* Target is a directory; build the full filename. */
  233.       char *new_dest;
  234.       PATH_BASENAME_CONCAT (new_dest, dest, source);
  235.       dest = new_dest;
  236.       /* Set this to nonzero to force another call to lstat
  237.      with the new destination.  */
  238.       lstat_status = 1;
  239.     }
  240.  
  241.   if (lstat_status == 0 || lstat (dest, &dest_stats) == 0)
  242.     {
  243.       if (S_ISDIR (dest_stats.st_mode))
  244.     {
  245.       error (0, 0, _("%s: cannot overwrite directory"), dest);
  246.       return 1;
  247.     }
  248.       if (interactive)
  249.     {
  250.       fprintf (stderr, _("%s: replace `%s'? "), program_name, dest);
  251.       if (!yesno ())
  252.         return 0;
  253.     }
  254.       else if (!remove_existing_files)
  255.     {
  256.       error (0, 0, _("%s: File exists"), dest);
  257.       return 1;
  258.     }
  259.  
  260.       if (backup_type != none)
  261.     {
  262.       char *tmp_backup = find_backup_file_name (dest);
  263.       if (tmp_backup == NULL)
  264.         error (1, 0, _("virtual memory exhausted"));
  265.       dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
  266.       strcpy (dest_backup, tmp_backup);
  267.       free (tmp_backup);
  268.       if (rename (dest, dest_backup))
  269.         {
  270.           if (errno != ENOENT)
  271.         {
  272.           error (0, errno, _("cannot backup `%s'"), dest);
  273.           return 1;
  274.         }
  275.           else
  276.         dest_backup = NULL;
  277.         }
  278.     }
  279.       else if (unlink (dest) && errno != ENOENT)
  280.     {
  281.       error (0, errno, _("cannot remove `%s'"), dest);
  282.       return 1;
  283.     }
  284.     }
  285.   else if (errno != ENOENT)
  286.     {
  287.       error (0, errno, "%s", dest);
  288.       return 1;
  289.     }
  290.  
  291.   if (verbose)
  292.     printf (_("create %s %s to %s\n"), LINK_TYPE,
  293.         dest, source);
  294.  
  295.   if ((*linkfunc) (source, dest) == 0)
  296.     {
  297.       return 0;
  298.     }
  299.  
  300.   error (0, errno, _("cannot create %s `%s' to `%s'"), LINK_TYPE,
  301.      dest, source);
  302.  
  303.   if (dest_backup)
  304.     {
  305.       if (rename (dest_backup, dest))
  306.     error (0, errno, _("cannot un-backup `%s'"), dest);
  307.     }
  308.   return 1;
  309. }
  310.  
  311. static void
  312. usage (int status)
  313. {
  314.   if (status != 0)
  315.     fprintf (stderr, _("Try `%s --help' for more information.\n"),
  316.          program_name);
  317.   else
  318.     {
  319.       printf (_("\
  320. Usage: %s [OPTION]... SOURCE [DEST]\n\
  321.   or:  %s [OPTION]... SOURCE... DIRECTORY\n\
  322. "),
  323.           program_name, program_name);
  324.       printf (_("\
  325. Link SOURCE to DEST (. by default), or multiple SOURCE(s) to DIRECTORY.\n\
  326. Makes hard links by default, symbolic links with -s.\n\
  327. \n\
  328.   -b, --backup                 make backups for removed files\n\
  329.   -d, -F, --directory          hard link directories (super-user only)\n\
  330.   -f, --force                  remove existing destinations\n\
  331.   -n, --no-dereference         treat destination that is a symlink to a\n\
  332.                                  directory as if it were a normal file\n\
  333.   -i, --interactive            prompt whether to remove destinations\n\
  334.   -s, --symbolic               make symbolic links instead of hard links\n\
  335.   -v, --verbose                print name of each file before linking\n\
  336.   -S, --suffix=SUFFIX          override the usual backup suffix\n\
  337.   -V, --version-control=WORD   override the usual version control\n\
  338.       --help                   display this help and exit\n\
  339.       --version                output version information and exit\n\
  340. \n\
  341. "));
  342.       printf (_("\
  343. The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX.  The\n\
  344. version control may be set with VERSION_CONTROL, values are:\n\
  345. \n\
  346.   t, numbered     make numbered backups\n\
  347.   nil, existing   numbered if numbered backups exist, simple otherwise\n\
  348.   never, simple   always make simple backups\n"));
  349.     }
  350.   exit (status);
  351. }
  352.  
  353. int
  354. main (int argc, char **argv)
  355. {
  356.   int c;
  357.   int errors;
  358.   int make_backups = 0;
  359.   char *version;
  360.  
  361.   program_name = argv[0];
  362.   setlocale (LC_ALL, "");
  363.   bindtextdomain (PACKAGE, LOCALEDIR);
  364.   textdomain (PACKAGE);
  365.  
  366.   version = getenv ("SIMPLE_BACKUP_SUFFIX");
  367.   if (version)
  368.     simple_backup_suffix = version;
  369.   version = getenv ("VERSION_CONTROL");
  370.  
  371.   linkfunc = link;
  372.   symbolic_link = remove_existing_files = interactive = verbose
  373.     = hard_dir_link = 0;
  374.   errors = 0;
  375.  
  376.   while ((c = getopt_long (argc, argv,
  377.                "bdfinsvFS:V:", long_options, (int *) 0))
  378.      != EOF)
  379.     {
  380.       switch (c)
  381.     {
  382.     case 0:            /* Long-named option. */
  383.        break;
  384.     case 'b':
  385.       make_backups = 1;
  386.       break;
  387.     case 'd':
  388.     case 'F':
  389.       hard_dir_link = 1;
  390.       break;
  391.     case 'f':
  392.       remove_existing_files = 1;
  393.       interactive = 0;
  394.       break;
  395.     case 'i':
  396.       remove_existing_files = 0;
  397.       interactive = 1;
  398.       break;
  399.     case 'n':
  400.       dereference_dest_dir_symlinks = 0;
  401.       break;
  402.     case 's':
  403. #ifdef S_ISLNK
  404.       symbolic_link = 1;
  405. #else
  406.       error (1, 0, _("symbolic links are not supported on this system"));
  407. #endif
  408.       break;
  409.     case 'v':
  410.       verbose = 1;
  411.       break;
  412.     case 'S':
  413.       simple_backup_suffix = optarg;
  414.       break;
  415.     case 'V':
  416.       version = optarg;
  417.       break;
  418.     default:
  419.       usage (1);
  420.       break;
  421.     }
  422.     }
  423.  
  424.   if (show_version)
  425.     {
  426.       printf ("ln - %s\n", PACKAGE_VERSION);
  427.       exit (0);
  428.     }
  429.  
  430.   if (show_help)
  431.     usage (0);
  432.  
  433.   if (optind == argc)
  434.     {
  435.       error (0, 0, _("missing file argument"));
  436.       usage (1);
  437.     }
  438.  
  439.   if (make_backups)
  440.     backup_type = get_version (version);
  441.  
  442. #ifdef S_ISLNK
  443.   if (symbolic_link)
  444.     linkfunc = symlink;
  445. #endif
  446.  
  447.   if (optind == argc - 1)
  448.     errors = do_link (argv[optind], ".");
  449.   else if (optind == argc - 2)
  450.     {
  451.       struct stat source_stats;
  452.       char *source;
  453.       char *dest;
  454.       char *new_dest;
  455.  
  456.       source = argv[optind];
  457.       dest = argv[optind + 1];
  458.  
  459.       /* When the destination is specified with a trailing slash and the
  460.      source exists but is not a directory, convert the user's command
  461.      `ln source dest/' to `ln source dest/basename(source)'.  */
  462.  
  463.       if (dest[strlen (dest) - 1] == '/'
  464.       && lstat (source, &source_stats) == 0
  465.       && !S_ISDIR (source_stats.st_mode))
  466.     {
  467.       PATH_BASENAME_CONCAT (new_dest, dest, source);
  468.     }
  469.       else
  470.     {
  471.       new_dest = dest;
  472.     }
  473.  
  474.       errors = do_link (source, new_dest);
  475.     }
  476.   else
  477.     {
  478.       char *to;
  479.  
  480.       to = argv[argc - 1];
  481.       if (!isdir (to))
  482.     error (1, 0, _("when making multiple links, last argument must be a directory"));
  483.       for (; optind < argc - 1; ++optind)
  484.     errors += do_link (argv[optind], to);
  485.     }
  486.  
  487.   exit (errors != 0);
  488. }
  489.